package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName: RegisterServiceImpl
 * @Author: 南风
 * @Email: 1480207032@qq.com
 * @Description:
 * @Date: 2020/7/11 16:23
 */
@Slf4j
@Service
public class RegisterServiceImpl implements IRegisterService {
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserVerifyMapper userVerifyMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String emailFrom;

    @Override
    public UserRegisterResponse register(UserRegisterRequest userRegisterRequest) {
        UserRegisterResponse userRegisterResponse = new UserRegisterResponse();

        // 判空验证
        userRegisterRequest.requestCheck();
        // 验证用户名是否重复
        validUsernameRepeated(userRegisterRequest);

        // 1、向用户表中插入一条数据
        Member member = new Member();
        member.setUsername(userRegisterRequest.getUserName());
        // password 要加密 Md5
        String userPassword = DigestUtils.md5DigestAsHex(userRegisterRequest.getUserPwd().getBytes());
        member.setPassword(userPassword);
        member.setEmail(userRegisterRequest.getEmail());
        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setIsVerified("N");
        member.setState(1);

        int memberRow = memberMapper.insert(member);
        if (memberRow != 1){
            // 插入失败
            userRegisterResponse.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            userRegisterResponse.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return userRegisterResponse;
        }

        // 2、向激活表中插入一条数据
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(userRegisterRequest.getUserName());
        userVerify.setRegisterDate(new Date());
        // uuid
        String key = member.getUsername() + member.getPassword() + UUID.randomUUID().toString();
        String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
        userVerify.setUuid(uuid);
        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");

        int userVerifyRow = userVerifyMapper.insert(userVerify);
        if (userVerifyRow != 1){
            userRegisterResponse.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            userRegisterResponse.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
            return userRegisterResponse;
        }

        new Thread(){
            @Override
            public void run() {
                // 3、发送邮件
                SimpleMailMessage message = new SimpleMailMessage();
                message.setFrom(emailFrom);
                message.setTo(userRegisterRequest.getEmail());
                message.setSubject("Mall 商城激活");
                //Long uid = getUserVerifyIdByUuid(uuid);
                message.setText("http://localhost:8080/user/verify?uuid=" + uuid  + "&username=" + userRegisterRequest.getUserName());
                javaMailSender.send(message);

                // 打印日志
                log.info("用户注册成功，注册参数request: {}", JSON.toJSONString(userRegisterRequest));
            }
        }.start();

        userRegisterResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        userRegisterResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

        return userRegisterResponse;
    }

    private Long getUserVerifyIdByUuid(String uuid) {
        Example example = new Example(UserVerify.class);
        example.createCriteria().andEqualTo("uuid", uuid);
        List<UserVerify> userVerifies = userVerifyMapper.selectByExample(example);
        UserVerify userVerify = userVerifies.size() >= 1 ? userVerifies.get(0):null;
        return userVerify.getId();
    }

    private void validUsernameRepeated(UserRegisterRequest userRegisterRequest) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", userRegisterRequest.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)){
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(),
                    SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
}
